import { addOrUpdateCase, saveFile, getManageCaseDetail } from '../../../../api/index'
const uploadOss = require('../../../../utils/upload/uploadImg.js')
import { uuid } from '../../../../utils/util'

Page({
  data: {
    showCatePicker: false,
    styleList: [],
    form: {
      projectName: '',
      styleId: '',
      styleStr: '',
      province: '',
      provinceVal: '',
      city: '',
      cityVal: '',
      region: '',
      regionVal: '',
      detailAddress: '',
      caseDate: '',
      type: 0,
      typeStr: '图片案例',
      projectDetail: '',
      banner: [],
    },
    showAddressPicker: false,
    showMaterialPicker: false,
    types: [
      { label: '图片案例', value: 0 },
      { label: '视频案例', value: 1 }
    ],
    selectIds: [],
    currentItem: {},
    currentIndex: 0
  },
  delMaterial ({ currentTarget: { dataset: { item, index } } }) {
    item.materialsList.splice(index, 1)
    let key = `form.banner[${this.data.currentIndex}].materialsList`
    this.setData({ [key]: item.materialsList })
  },
  addMaterial ({ currentTarget: { dataset: { item, index } } }) {
    let ids = []
    if (item.materialsList && item.materialsList.length) ids = item.materialsList.map(item => { return item.id })
    this.setData({ showMaterialPicker: true, selectIds: ids, currentItem: item, currentIndex: index })
  },
  closeMaterialModal () {
    this.setData({ showMaterialPicker: false })
  },
  confirmMaterial ({ detail }) {
    this.data.form.banner[this.data.currentIndex].materialsList.push(...detail)
    let key = `form.banner[${this.data.currentIndex}].materialsList`
    this.setData({ [key]: this.data.form.banner[this.data.currentIndex].materialsList, showMaterialPicker: false })
  },
  selectStyle () {
    this.setData({ showCatePicker: true })
  },
  closeStyleModal () {
    this.setData({ showCatePicker: false })
  },
  changeStyle ({ detail }) {
    let sections = detail.filter(item => item.isSelect)
    let styleStr = sections.map(item => { return item.styleName }).join(',')
    let styleId = sections.map(item => { return item.styleId }).join(',')
    this.setData({
      'form.styleStr': styleStr,
      'form.styleId': styleId,
      showCatePicker: false
    })
  },
  selectAddress () {
    this.setData({ showAddressPicker: true })
  },
  closeModal () {
    this.setData({ showAddressPicker: false })
  },
  confirm ({ detail }) {
    this.setData({
      'form.province': detail[0].value,
      'form.provinceVal': detail[0].label,
      'form.city': detail[1].value,
      'form.cityVal': detail[1].label,
      'form.region': detail[2].value,
      'form.regionVal': detail[2].label,
      showAddressPicker: false
    })
  },
  async changeDate ({ detail: { value } }) {
    try {
      this.setData({ 'form.caseDate': value })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  deleteFile ({ currentTarget: { dataset: { item, index } } }) {
    this.data.form.banner.splice(index, 1)
    this.setData({ 'form.banner': this.data.form.banner })
  },
  changeType ({ detail: { value } }) {
    this.setData({ 'form.type': this.data.types[value].value, 'form.typeStr': this.data.types[value].label, 'form.banner': [] })
  },
  changeInput ({ currentTarget: { dataset: { key } }, detail: { value } }) {
    this.setData({ ['form.' + key]: value })
  },
  toggleMore ({ currentTarget: { dataset: { item, index } } }) {
    item.moreCount = 99999999999999
    let key = `form.banner[${index}]`
    this.setData({ [key]: item })
  },
  addFile ({ target: { dataset: { key, num } } }) {
    let _this = this
    if (num - this.data.form.banner.length <= 0) {
      wx.showToast({ title: `最多可以上传${num}${parseInt(_this.data.form.type) === 1 ? '个案例视频' : '张案例图片'}`, icon: 'none' })
      return
    }
    let type = ['image']
    if (parseInt(_this.data.form.type) === 1) {
      type = ['video']
    }
    wx.chooseMedia({
      count: parseInt(num),
      mediaType: type,
      async success (res) {
        res.tempFiles.forEach(item => {
          item.uuid = uuid()
          item.progress = 0
        })
        let tempFiles = res.tempFiles
        let temFileList = []
        if (tempFiles.length) {
          temFileList = await Promise.all(tempFiles.map(async (item, index) => {
            const file = await _this.uploadFile(item, 'tempFilePath', tempFiles, index, _this, key)
            if (file) {
              const { ResultSet } = await saveFile({
                fileList: [{
                  fileSize: item.size,
                  fileName: file.fileName,
                  fileUrl: file.fileUrl
                }]
              })
              let reItem = {
                uuid: item.uuid,
                picId: ResultSet.userData.fileIdList[0].fileId,
                fileName: file.fileName,
                picUrl: ResultSet.userData.fileIdList[0].fileUrl,
                fileUrl: ResultSet.userData.fileIdList[0].url,
                moreCount: 3,
                materialsList: []
              }
              if (parseInt(_this.data.form.type) === 1) {
                let duration = item.duration * 60
                let minute = parseInt(duration / 60)
                let second = parseInt(duration % 60)
                let minuteStr = ''
                let secondStr = ''
                if (minute < 9) {
                  minuteStr = `0${minute}`
                } else {
                  minuteStr = minute
                }
                if (second < 9) {
                  secondStr = `0${second}`
                } else {
                  secondStr = second
                }
                reItem.duration = `${minuteStr}:${secondStr}`
              }
              return reItem
            } else {
              tempFiles[index].success = 1
              _this.setData({
                [`${key}`]: tempFiles
              })
            }
          }))
        }
        let tempFileList = temFileList.filter(item => item)
        _this.data.form[key].push(...tempFileList)
        _this.data.form[key].forEach((item) => {
          let rowIndex = tempFiles.findIndex(row => row.uuid === item.uuid)
          if (rowIndex > -1) tempFiles.splice(rowIndex, 1)
        })
        _this.setData({
          [`${key}`]: tempFiles,
          [`form.${key}`]: _this.data.form[key]
        })
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          resolve()
        },
        files, index, that, dataKey
      )
    })
  },
  async submit () {
    try {
      if (!this.data.form.projectName) {
        wx.showToast({ title: '请输入案例名称！', icon: 'none' })
        return
      }
      if (!this.data.form.styleId) {
        wx.showToast({ title: '请选择所属业态！', icon: 'none' })
        return
      }
      if (!this.data.form.province && !this.data.form.city && !this.data.form.detailAddress) {
        wx.showToast({ title: '请选择并填写详细地址！', icon: 'none' })
        return
      }
      if (!this.data.form.caseDate) {
        wx.showToast({ title: '请选择项目时间！', icon: 'none' })
        return
      }
      if (!this.data.form.banner.length) {
        wx.showToast({ title: '请选择案例图片！', icon: 'none' })
        return
      }
      if (!this.data.form.projectDetail) {
        wx.showToast({ title: '请输入案例详情！', icon: 'none' })
        return
      }
      wx.showLoading({ title: '提交中...', mask: true })
      await addOrUpdateCase({ ...this.data.form })
      wx.hideLoading()
      wx.$nav.navigateBack()
    } catch (err) {
      wx.hideLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async getDetail () {
    try {
      const { ResultSet } = await getManageCaseDetail({ materialCaseId: this.data.form.materialCaseId })
      this.data.form = { ...this.data.form, ...ResultSet.userData.Information.materialCaseInf }
      this.data.form.styleStr = ResultSet.userData.Information.style.map(item => { return item.styleName }).join(',')
      ResultSet.userData.picture.forEach(item => {
        item.moreCount = 3
      })
      this.data.form.banner = ResultSet.userData.picture
      this.setData({ form: this.data.form })
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad ({ id }) {
    if (id) {
      wx.$pro.setNavigationBarTitle({ title: '编辑案例' })
      this.setData({ 'form.materialCaseId': id })
      this.getDetail()
    } else {
      wx.$pro.setNavigationBarTitle({ title: '发布案例' })
    }
  }
})